/// copy from koa-respond
"use strict";
import * as Koa from 'koa'

/**
 * Makes the respond middleware. 
 * @return {Function}
 */
function makeRespondMiddleware(): Koa.Middleware {

    // Make the respond function.
    function respond(ctx: Koa.Context, code: string, message: string, payload: any) {
        // ctx.status = 200  //200是 默认值不用再赋值
        ctx.body = {
            c: code,
            m: message,
            d: payload
        }
        return ctx
    }

    /**
     * Installs the functions in the context.
     *
     * @param  {KoaContext} ctx
     */
    function patch(ctx: Koa.Context) {
        // const statusMethods = Object.assign({}, opts.statusMethods, statusCodeMap)
        ctx.send = respond.bind(ctx, ctx)
        ctx.ok = respond.bind(ctx, ctx, "200", "ok")
        ctx.error = respond.bind(ctx, ctx, "500", "err")

        /*   // Bind status methods.
          for (const method in statusMethods) {
              const code = statusMethods[method]
              ctx[method] = respond.bind(ctx, ctx, [code, method])
          } */
        //  allow Koa 1 users才需要return
        // return ctx
    }

    /**
     * The respond middleware adds the methods to the context.
     *
     * @param  {KoaContext} ctx
     */
    function respondMiddleware(ctx: Koa.Context, next: Koa.Next) {
        patch(ctx)
        return next()
    }

    // Tack on the patch method to allow Koa 1 users
    // to install it, too.
    // respondMiddleware.patch = patch
    return respondMiddleware
}

export default makeRespondMiddleware
